package com.linxcool.ui;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.linxcool.util.SystemUtil;

/**
 * 图片加载器
 * @author: 胡昌海(linxcool.hu)
 */
public class ImageLoader implements Runnable{
	
	static final int TIME_FOR_RETRY = 3000;
	static final int COUNTS_FOR_RETRY = 3;
	int count = 0;
	
	/**
	 * 输入流过滤器
	 * <p>兼容低版本解析网络图片产生 decoder->decode returned false 错误
	 * @author: 胡昌海(linxcool.hu)
	 */
	public static class FlushedInputStream extends FilterInputStream{

		protected FlushedInputStream(InputStream in) {
			super(in);
		}

		@Override
		public long skip(long count) throws IOException {
			long totalSkipped = 0;
			while(totalSkipped < count){
				long needSkip = count - totalSkipped;
				long resultSkip = in.skip(needSkip);
				if(resultSkip == 0L){
					int b = in.read();
					if(b < 0) break;
					else resultSkip = 1;
				}
				else ;//Empty
				totalSkipped += resultSkip;
			}
			return totalSkipped;
		}
	}
	
	Bitmap loadNetBitmap(Context context,String url){
		InputStream is = null;
		try {
			URL imgUrl = new URL(url);
			
			URLConnection connection = null;
			//添加网络代理
			if(SystemUtil.getProxy(context)!=null){
				Proxy proxy = new Proxy(
						Proxy.Type.HTTP,new InetSocketAddress("10.0.0.172", 80));  
				connection = imgUrl.openConnection(proxy);
			}else{
				connection = imgUrl.openConnection();
			}
			connection.connect();
			 
			is = connection.getInputStream();
			
			Bitmap bitmap = BitmapFactory.decodeStream(new FlushedInputStream(is));
			return bitmap;
		} catch (Exception e) {
			if(count < COUNTS_FOR_RETRY){
				try {
					Thread.sleep(TIME_FOR_RETRY);
				} catch (InterruptedException iE) {}
				count++;
				return loadNetBitmap(context,url);
			}
			else{
				e.printStackTrace();
			}
		}finally{
			try {
				if(is!=null)is.close();
			} catch (IOException e) {}
		}
		return null;
	}
	
	@Override
	public void run() {
		
	}

}
